package game.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import common.model.po.GMilestone;
import common.model.po.GMilestoneRequirement;
import common.model.po.GMilestoneUnlock;
import common.model.response.base.Result;
import game.mapper.GMilestoneMapper;
import game.model.converter.GMilestoneConverter;
import game.model.request.SaveMilestoneRequest;
import game.service.GMilestoneRequirementService;
import game.service.GMilestoneService;
import game.service.GMilestoneUnlockService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 服务实现类
 *
 * @author 米泽鹏
 * @since 2024-01-19 下午 05:05
 */
@Service
public class GMilestoneServiceImpl extends ServiceImpl<GMilestoneMapper, GMilestone> implements GMilestoneService {

	@Resource
	private GMilestoneMapper mapper;
	@Resource
	private GMilestoneRequirementService requirementService;
	@Resource
	private GMilestoneUnlockService unlockService;

	@Override
	public List<List<GMilestone>> getAllMilestone() {
		List<GMilestone> milestoneList = lambdaQuery().orderByAsc(GMilestone::getLevel).orderByAsc(GMilestone::getSort).list();
		Map<Integer, List<GMilestone>> map = milestoneList.stream().collect(Collectors.groupingBy(GMilestone::getLevel, LinkedHashMap::new, Collectors.toList()));
		List<List<GMilestone>> result = Lists.newArrayList();
		map.keySet().stream().sorted().forEach(key -> result.add(map.get(key)));
		return result;
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public Result<?> saveMilestone(SaveMilestoneRequest request) {
		GMilestone milestone = GMilestoneConverter.saveRequestToPo(request);
		List<GMilestoneRequirement> requirementList = request.getRequirementList();
		List<GMilestoneUnlock> unlockList = request.getUnlockList();
		// 里程碑
		if (milestone.getId() == null) {
			milestone.insert();
		} else {
			milestone.updateById();
			// 删除现有的成本项和解锁项
			requirementService.lambdaUpdate().eq(GMilestoneRequirement::getMilestoneId, milestone.getId()).remove();
			unlockService.lambdaUpdate().eq(GMilestoneUnlock::getMilestoneId, milestone.getId()).remove();
		}
		// 新增成本项和解锁项
		requirementList.forEach(requirement -> requirement.setMilestoneId(milestone.getId()));
		unlockList.forEach(unlock -> unlock.setMilestoneId(milestone.getId()));
		requirementService.saveBatch(requirementList);
		unlockService.saveBatch(unlockList);
		return Result.success();
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public Result<?> deleteMilestone(Long id) {
		removeById(id);
		requirementService.lambdaUpdate().eq(GMilestoneRequirement::getMilestoneId, id).remove();
		unlockService.lambdaUpdate().eq(GMilestoneUnlock::getMilestoneId, id).remove();
		return Result.success();
	}

}
